package com.ruoyi.exam.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.constant.ExamConstans;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.exam.domain.QuestionBank;
import com.ruoyi.exam.domain.req.ExamineReq;
import com.ruoyi.exam.domain.vo.ExamGeneratingPaperVO;
import com.ruoyi.exam.domain.vo.ExamineVO;
import com.ruoyi.exam.mapper.QuestionBankMapper;
import com.ruoyi.exam.service.IQuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.exam.mapper.ExamineMapper;
import com.ruoyi.exam.domain.Examine;
import com.ruoyi.exam.service.IExamineService;
import org.springframework.util.CollectionUtils;

/**
 * 考试管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-01
 */
@Service
public class ExamineServiceImpl implements IExamineService 
{


    @Autowired
    private ExamineMapper examineMapper;

    @Autowired
    private QuestionBankMapper questionBankMapper;

    /**
     * 查询考试管理
     * 
     * @param id 考试管理主键
     * @return 考试管理
     */
    @Override
    public Examine selectExamineById(Long id)
    {
        return examineMapper.selectExamineById(id);
    }

    /**
     * 查询考试管理列表
     * 
     * @param examine 考试管理
     * @return 考试管理
     */
    @Override
    public List<Examine> selectExamineList(Examine examine)
    {
        return examineMapper.selectExamineList(examine);
    }

    /**
     * 新增考试管理
     * 
     * @param examine 考试管理
     * @return 结果
     */
    @Override
    public int insertExamine(Examine examine)
    {
        examine.setCreateTime(DateUtils.getNowDate());
        return examineMapper.insertExamine(examine);
    }

    /**
     * 修改考试管理
     * 
     * @param examine 考试管理
     * @return 结果
     */
    @Override
    public int updateExamine(Examine examine)
    {
        examine.setUpdateTime(DateUtils.getNowDate());
        return examineMapper.updateExamine(examine);
    }

    /**
     * 批量删除考试管理
     * 
     * @param ids 需要删除的考试管理主键
     * @return 结果
     */
    @Override
    public int deleteExamineByIds(Long[] ids)
    {
        return examineMapper.deleteExamineByIds(ids);
    }

    /**
     * 删除考试管理信息
     * 
     * @param id 考试管理主键
     * @return 结果
     */
    @Override
    public int deleteExamineById(Long id)
    {
        return examineMapper.deleteExamineById(id);
    }

    @Override
    public int addExam(ExamineVO examine) {
        Examine examineDB = BeanUtil.toBean(examine, Examine.class);
        List<ExamGeneratingPaperVO> examGeneratingPaper = examine.getExamGeneratingPaper();
        String examGeneratingPaperJson = JSONUtil.toJsonStr(examGeneratingPaper);
        examineDB.setExamGeneratingPaper(examGeneratingPaperJson);
        return examineMapper.insertExamine(examineDB);
    }

    @Override
    public int updateExamineVO(ExamineVO examine) {
        Examine examineDB = BeanUtil.toBean(examine, Examine.class);
        List<ExamGeneratingPaperVO> examGeneratingPaper = examine.getExamGeneratingPaper();
        String examGeneratingPaperJson = JSONUtil.toJsonStr(examGeneratingPaper);
        examineDB.setExamGeneratingPaper(examGeneratingPaperJson);
        return examineMapper.updateExamine(examineDB);
    }

    @Override
    public int addExamine(ExamineReq examineReq) {
        //优先判断不查询数据库的逻辑
        checkExam(examineReq);
        //如果逻辑正确，则进行数据库操作
       //组装数据库对象
        Examine examine = buildExamine(examineReq);
        if(examineReq.getId()!=null){
            return  examineMapper.updateExamine(examine);
        }else {
            return examineMapper.insertExamine(examine);
        }
    }

    private Examine buildExamine(ExamineReq examineReq) {
        Examine examine = BeanUtil.copyProperties(examineReq, Examine.class);
        String examGeneratingPaperJson = JSONUtil.toJsonStr(examineReq.getExamGeneratingPaperList());
        examine.setExamGeneratingPaper(examGeneratingPaperJson);
        return examine;
    }

    private void checkExam(ExamineReq examineReq) {
        List<ExamGeneratingPaperVO> examGeneratingPaperList = examineReq.getExamGeneratingPaperList();
        int totalPoints = 0;
        for (ExamGeneratingPaperVO examGeneratingPaperVO : examGeneratingPaperList) {
            totalPoints += examGeneratingPaperVO.getSingleChoiceSelectCount()*examGeneratingPaperVO.getSingleChoiceScore()
                    +examGeneratingPaperVO.getMultipleChoiceSelectCount()*examGeneratingPaperVO.getMultipleChoiceScore()
                    +examGeneratingPaperVO.getTrueorfalseQuestionsSelectCount()*examGeneratingPaperVO.getTrueorfalseQuestionsScore();
        }
        if(totalPoints<=0){
            throw new RuntimeException("考试规则设置不正确，请确认!");
        }

        List<Long> questionBlankIdList = examGeneratingPaperList.stream().map(ExamGeneratingPaperVO::getQuestionBlankId).collect(Collectors.toList());
        List<QuestionBank> questionBankListByDB = questionBankMapper.selectQuestionsBankByIds(questionBlankIdList);
        if(CollectionUtils.isEmpty(questionBankListByDB)){
            throw new RuntimeException("题库中不存在，请确认!");
        }
        if(questionBankListByDB.size() != examGeneratingPaperList.size()){
            throw new RuntimeException("题库中不存在，请确认!");
        }
        if( examineReq.getIsTimeLimit() !=null && examineReq.getIsTimeLimit() == ExamConstans.YES_TIME_LIMIT){
           if(examineReq.getExamStartTime()==null || examineReq.getExamStopTime()==null){
               throw new RuntimeException("考试规则设置不正确，请确认!");
           }
        }
    }


}
